package com.fxp.project.jiuselu.web.models.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxp.project.jiuselu.commons.exceptions.JiuLuException;
import com.fxp.project.jiuselu.commons.name.Language;
import com.fxp.project.jiuselu.commons.name.RandomNameTool;
import com.fxp.project.jiuselu.commons.utils.CommonUtil;
import com.fxp.project.jiuselu.web.domain.CommonResult;
import com.fxp.project.jiuselu.web.models.user.entity.JslSaleInfo;
import com.fxp.project.jiuselu.web.models.user.entity.JslUser;
import com.fxp.project.jiuselu.web.models.user.entity.JslUserOauth;
import com.fxp.project.jiuselu.web.models.user.mapper.JslSaleInfoMapper;
import com.fxp.project.jiuselu.web.models.user.mapper.JslUserMapper;
import com.fxp.project.jiuselu.web.models.user.request.ReqRegSalesMan;
import com.fxp.project.jiuselu.web.models.user.service.IJslSaleInfoService;
import com.fxp.project.jiuselu.web.models.user.service.IJslUserOauthService;
import com.fxp.project.jiuselu.web.models.user.service.IJslUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 销售员信息表 服务实现类
 * </p>
 *
 * @author Jason.Wang
 * @since 2021-11-01
 */
@Service
public class JslSaleInfoServiceImpl extends ServiceImpl<JslSaleInfoMapper, JslSaleInfo> implements IJslSaleInfoService {

    @Autowired
    JslSaleInfoMapper jslSaleInfoMapper;
    @Autowired
    IJslUserService jslUserService;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    IJslUserOauthService jslUserOauthService;
    @Autowired
    JslUserMapper jslUserMapper;

    /**
     * saveOrUpdateToApply: 更新创建销售员申请<br/>
     *
     * @param userId
     * @param reqRegSalesMan
     * @return
     * @author Kai.Wang
     * @date 2021/11/1 14:13
     */
    @Override
    public CommonResult saveOrUpdateToApply(Long userId, ReqRegSalesMan reqRegSalesMan) {
//        JslSaleInfo jslSaleInfo = jslSaleInfoMapper.selectById(userId);
        JslSaleInfo jslSaleInfo= jslSaleInfoMapper.selectOne(new QueryWrapper<JslSaleInfo>().lambda().eq(JslSaleInfo::getSalePhone,reqRegSalesMan.getSalePhone()));
        if (null != jslSaleInfo) {
            // 判断当前状态是否允许重新编辑业务员信息
            if (1 == jslSaleInfo.getStatus()) {
                return CommonResult.failed( "当前申请已通过请勿重复申请");
            }
            // 添加更新时间
            jslSaleInfo.setUpdateTime(CommonUtil.getCurrentDateTime());
            jslSaleInfo.setRemark("");
            // 处于审核状态
            jslSaleInfo.setStatus(0);
            BeanUtils.copyProperties(reqRegSalesMan, jslSaleInfo);
            jslSaleInfoMapper.updateById(jslSaleInfo);
        } else {
            //绑定代理user
            JslUser jslUser = new JslUser();
            jslUser.setUserPhone(reqRegSalesMan.getSalePhone());
            jslUser.setCreateTime(CommonUtil.getCurrentDateTime());
            jslUser.setNickName(RandomNameTool.getName(Language.zh, 0));
            jslUser.setInviteNum(0L);
            jslUser.setLevel(1);
            jslUser.setInviteId(reqRegSalesMan.getInviteCode());
            jslUser.setPassword("123456");
            jslUserService.save(jslUser);


            jslSaleInfo = new JslSaleInfo();
            //绑定userId
            jslSaleInfo.setBindId(jslUser.getUserId());
            // 处于审核状态
            jslSaleInfo.setStatus(0);
            // 当前注册时间
            jslSaleInfo.setCreateTime(CommonUtil.getCurrentDateTime());
            BeanUtils.copyProperties(reqRegSalesMan, jslSaleInfo);
            jslSaleInfoMapper.insert(jslSaleInfo);
        }
        return CommonResult.success("");
    }

    @Override
    public CommonResult salesman(ReqRegSalesMan reqRegSalesMan) {
        JslSaleInfo jslSaleInfo = jslSaleInfoMapper.selectOne(new QueryWrapper<JslSaleInfo>().lambda().eq(JslSaleInfo::getSalePhone, reqRegSalesMan.getSalePhone()));
        if (null != jslSaleInfo) {
            // 判断当前状态是否允许重新编辑业务员信息
            if (1 == jslSaleInfo.getStatus()) {
                return CommonResult.success("500", "该手机号已提交申请，请勿重复提交");
            }
            // 添加更新时间
            jslSaleInfo.setUpdateTime(CommonUtil.getCurrentDateTime());
            jslSaleInfo.setCreateTime(LocalDateTime.now());
            jslSaleInfo.setRemark("");
            // 处于审核状态
            jslSaleInfo.setStatus(0);
            BeanUtils.copyProperties(reqRegSalesMan, jslSaleInfo);
//            JslUser user = jslUserService.getOne(new QueryWrapper<JslUser>().eq("user_id", reqRegSalesMan.getInviteCode()));
            JslUser jslUser = jslUserService.getOne(new QueryWrapper<JslUser>().eq("user_id", jslSaleInfo.getBindId()));
            jslUser.setInviteId(reqRegSalesMan.getInviteCode());
            jslUserService.updateById(jslUser);
            jslSaleInfoMapper.updateById(jslSaleInfo);

            return CommonResult.success("200","");
        } else {
            jslSaleInfo = new JslSaleInfo();
            // 处于审核状态
            jslSaleInfo.setStatus(0);
            // 当前注册时间
            jslSaleInfo.setCreateTime(CommonUtil.getCurrentDateTime());

            BeanUtils.copyProperties(reqRegSalesMan, jslSaleInfo);

            JslUser jslUser = jslUserService.getOne(new QueryWrapper<JslUser>().lambda().eq(JslUser::getUserPhone,reqRegSalesMan.getSalePhone()).eq(JslUser::getLevel,1));

            Long userId = null;
            if (jslUser==null){
                //注册代理user
                jslUser = new JslUser();
                jslUser.setUserPhone(reqRegSalesMan.getSalePhone());
                jslUser.setCreateTime(CommonUtil.getCurrentDateTime());
                jslUser.setNickName(RandomNameTool.getName(Language.zh, 0));
                jslUser.setInviteNum(0L);
                jslUser.setLevel(1);
                jslUser.setInviteId(reqRegSalesMan.getInviteCode());
                jslUser.setPassword("123456");
                jslUser.setUserId(jslUserMapper.selectNewUser().getUserId()+1);
                jslUserService.save(jslUser);
                if(reqRegSalesMan.getType()!=null && reqRegSalesMan.getOpenId() !=null){
                    JslUserOauth userOauth=new JslUserOauth();
                    userOauth.setOpenid(reqRegSalesMan.getOpenId());
                    JslUser jslUser1 = jslUserService.selectByUserPhoneAndLevle(reqRegSalesMan.getSalePhone(),1);
                    if(jslUser1 != null){
                        userOauth.setUserId(jslUser.getUserId());
                        userOauth.setOauth("1");
                        userOauth.setOauthType(1);
                        jslUserOauthService.save(userOauth);
                    }
                }
                userId=jslUser.getUserId();
            }else {
                userId=jslUser.getUserId();
            }
//            else {
//                return CommonResult.failed("该手机号已在普通用户注册，请在普通用户申请业务员");
//            }
//            jslSaleInfo.setUserId(userId);
            jslSaleInfo.setSaleSex(reqRegSalesMan.getSaleSex());
            jslSaleInfo.setBindId(userId);
            try {
                jslSaleInfoMapper.insert(jslSaleInfo);
            }catch (Exception e){
                return CommonResult.failed("该手机号已被注册");
            }

        }
        return CommonResult.success("200", "");
    }


    /**
     * getByUserId: 通过用户的UserId获取当前销售员信息<br/>
     *
     * @param userId
     * @return
     * @author Kai.Wang
     * @date 2021/11/1 14:20
     */
    @Override
    public JslSaleInfo getByUserId(Long userId) {
        return jslSaleInfoMapper.selectById(userId);
    }

    @Override
    public JslSaleInfo selectSaleInfoByBindId(Long bindId) {
        return jslSaleInfoMapper.selectSaleInfoByBindId(bindId);
    }
}
